package com.hesir.api2entity.services;

import com.hesir.api2entity.pojo.ApiEntity;
import lombok.extern.log4j.Log4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class Excelhandler {

    @Autowired
    ResourceLoader resourceLoader;

    private final static Logger log = LoggerFactory.getLogger(Excelhandler.class);

    /**
     * @Author hetianxing
     * @Description  读取Excelsheet的行列数据并生成文件
     * @Date  2019/12/23 14:41
     * @Param []
     * @return java.lang.String
     **/
    public String process() throws FileNotFoundException {
        Resource resource = resourceLoader.getResource("classpath:./excel/tongcheng.xlsx");

        try {
            File file = new File(resource.getURI().getPath());
            Workbook wb = WorkbookFactory.create(file);
            HashMap<String, List<ApiEntity>> map = new HashMap<>();
            //读取
            for (Sheet sheet:wb){
                //获取实际行数
                int arows = sheet.getPhysicalNumberOfRows()-1;

                List<ApiEntity> entities = new ArrayList<>();
                int i = 0;
                for (Row row:sheet)
                {
                    if(i==arows){
                        break;
                    }
                    if (sheet.getRow(i).getRowNum()==0){
                        i++;
                        continue;
                    }
                    ApiEntity entity = new ApiEntity();
                    entity.setName(String.valueOf(row.getCell(0)));
                    entity.setType(String.valueOf(row.getCell(1)));
                    entity.setRequired(String.valueOf(row.getCell(2)));
                    entity.setComment(String.valueOf(row.getCell(3)));
                    entities.add(entity);
                    i++;
                }
                log.info("sheet-name:{},list:{}",sheet.getSheetName(),entities);
                createFile(sheet.getSheetName(),entities,true);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return  "";
    }

    /**
     * @Author hetianxing
     * @Description  生成Java文件
     * @Date  2019/12/23 14:40
     * @Param [fileName] 文件名
     * @Param [apiEntities] 字段列表
     * @Param [useCamel] 是否使用驼峰命名
     * @return void
     **/
    private void createFile(String fileName, List<ApiEntity> apiEntities,boolean useCamel){
        File file = new File("/Volumes/Data/WorkSpace/api2entity/src/main/java/com/hesir/api2entity/entity/"+fileName+".java");
        FileOutputStream  fos = null;
        try {
            fos = new FileOutputStream(file);
            StringBuilder str = new StringBuilder();
            str.append("package com.hesir.api2entity.entity;\n" +
                    "\n" +
                    "import lombok.Data;\n" +
                    "\n");
            str.append("@Data\n@ApiModel(value = \"参数说明\")\n");
            str.append("public class "+fileName+" {\n");
            for (ApiEntity entity:apiEntities){
                String required = "";
                if ("是".equals(entity.getRequired().trim())){
                    required = "true";
                }else{
                    required = "false";
                }

                str.append("\t@ApiModelProperty(value = \""+entity.getComment()+"\", required = "+required+")\n");

                String title = entity.getName();
                if (useCamel){
                    title = CamelConvert.underline2Camel(title);
                }
                str.append("\tprivate "+entity.getType()+" "+title+"; \n");
            }
            str.append("}");

            byte[] bytes = str.toString().getBytes();
            fos.write(bytes);
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * @Author hetianxing
     * @Description  将下划线字段转换为驼峰格式
     * @Date  2019/12/23 14:40
     * @Param
     * @return
     **/
    public static class CamelConvert{
        public static final char UNDERLINE_CHAR = '_';

        /**
         * 下划线转驼峰
         *
         * @param underlineStr
         * @return
         */
        public static String underline2Camel(String underlineStr) {

            if (StringUtils.isEmpty(underlineStr)) {

                return "";
            }

            int len = underlineStr.length();
            StringBuilder strb = new StringBuilder(len);
            for (int i = 0; i < len; i++) {

                char c = underlineStr.charAt(i);
                if (c == UNDERLINE_CHAR && (++i) < len) {

                    c = underlineStr.charAt(i);
                    strb.append(Character.toUpperCase(c));
                } else {

                    strb.append(c);
                }
            }
            return strb.toString();
        }
    }
}
